package com.dy.yunying.biz.service.datacenter.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dy.yunying.api.datacenter.dto.AdDataDto;
import com.dy.yunying.api.datacenter.dto.AdOverviewDto2;
import com.dy.yunying.api.datacenter.vo.AdDataVo;
import com.dy.yunying.api.entity.ParentGameDO;
import com.dy.yunying.api.req.ChannelManageReq;
import com.dy.yunying.api.vo.ChannelManageVo;
import com.dy.yunying.biz.dao.datacenter.impl.AdDataDao;
import com.dy.yunying.biz.service.datacenter.AdDataService;
import com.dy.yunying.biz.service.manage.AdRoleUserService;
import com.dy.yunying.biz.service.manage.ChannelManageService;
import com.dy.yunying.biz.service.manage.ParentGameService;
import com.pig4cloud.pig.api.feign.RemoteAccountService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 广告数据报表相关方法
 *
 * @author ：lile
 * @date ：2021/6/17 14:00
 * @description：
 * @modified By：
 */
@Log4j2
@Service(value = "dcAdDataServiceImpl")
@RequiredArgsConstructor
public class AdDataServiceImpl implements AdDataService {

	private final AdDataDao adDataDaoNew;

	private final AdRoleUserService adRoleUserService;

	private final RemoteAccountService remoteAccountService;

	private final ParentGameService parentGameService;

	private final ChannelManageService channelManageService;

	/**
	 * 广告数据报表总数
	 *
	 * @param req
	 * @return
	 */
	@Override
	public R countDataTotal(AdDataDto req) {
		Long count = null;
		try {
			this.managerParam(req);

			count = adDataDaoNew.countDataTotal(req);
		} catch (Exception e) {
			log.error("countDataTotal:[{}]", e);
			return R.failed("广告数据报表总记录数查询失败");
		}
		return R.ok(count);
	}

	/**
	 * 广告数据报表分页数据
	 *
	 * @param req
	 * @return
	 */
	@Override
	public R selectAdDataSource(AdDataDto req) {
		this.managerParam(req);

		List<AdDataVo> resultData = adDataDaoNew.selectAdDataSource(req); // 查询数据
		//处理报表数据
		deal(resultData);
		return R.ok(resultData);
	}

	private void managerParam(AdDataDto req){
		// 判断是否管理员
		if (SecurityUtils.getRoles().contains(1)) {
			req.setIsSys(1);
		} else {
			// 当前用户
			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			req.setRoleUserIdList(roleUserIdList);
			roleUserIdList.add(user.getId());
			roleUserIdList.addAll(ownerRoleUserIds);

			// 授权的广告账户
			List<String> roleAdAccountList = new ArrayList<>();
			req.setRoleAdAccountList(roleAdAccountList);
			final List<String> accountList2 = adRoleUserService.getThrowAccountList();
			if (ObjectUtils.isNotEmpty(accountList2)) {
				roleAdAccountList.addAll(accountList2);
			}
		}
	}
	/**
	 * 广告数据报表导出
	 *
	 * @param req
	 * @return
	 */
	@Override
	public List<AdDataVo> excelAdDataSource(AdDataDto req) {

		// 当前用户
		final PigUser user = SecurityUtils.getUser();
		List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
		// 当前账号及管理的账号
		List<Integer> roleUserIdList = new ArrayList<>();
		req.setRoleUserIdList(roleUserIdList);
		roleUserIdList.add(user.getId());
		roleUserIdList.addAll(ownerRoleUserIds);

		// 授权的广告账户
		List<String> roleAdAccountList = new ArrayList<>();
		req.setRoleAdAccountList(roleAdAccountList);
		final List<String> accountList2 = remoteAccountService.getAccountList2(ownerRoleUserIds, SecurityConstants.FROM_IN);

		if (ObjectUtils.isNotEmpty(accountList2)) {
			roleAdAccountList.addAll(accountList2);
		}

		// 判断是否管理员
		if (SecurityUtils.getRoles().contains(1)) {
			req.setIsSys(1);
		}

		List<AdDataVo> resultData1 = adDataDaoNew.selectAdDataSource(req); // 查询数据
		//处理报表数据
		deal(resultData1);
		if (StringUtils.isNotBlank(req.getQueryColumn()) || 5 != req.getCycleType()) {
			// 如果导出的数据是非汇总的，则需要再导出一行汇总数据
			req.setQueryColumn(StringUtils.EMPTY);
			req.setCycleType(5);
			List<AdDataVo> resultData2 = adDataDaoNew.selectAdDataSource(req); // 查询汇总数据
			deal(resultData2);
			resultData1.addAll(resultData2);
		}

		return resultData1;
	}

	private void deal(List<AdDataVo> adRecoveryVos) {
		if (CollectionUtils.isNotEmpty(adRecoveryVos)) {

			//主渠道编码
			Map<String, String> map = new HashMap<>();
			ChannelManageReq req = new ChannelManageReq();
			IPage<ChannelManageVo> data = channelManageService.queryParentchlList(req);
			if (CollectionUtils.isEmpty(data.getRecords())) {
				List<ChannelManageVo> list = data.getRecords();
				map = list.stream().collect(Collectors.toMap(
						o -> {
							return String.valueOf(o.getChncode());
						}, ChannelManageVo::getChnname));
			}
			Map<String, String> finalMap = map;
			adRecoveryVos.forEach(dataList -> {
				String parentchl = dataList.getParentchl();
				dataList.setParentchlName(finalMap.get(parentchl) == null ? parentchl : finalMap.get(parentchl));

			});

			for (AdDataVo adRecoveryVo : adRecoveryVos) {
				try {
					final Long pgid = adRecoveryVo.getPgid();

					final ParentGameDO parentGameDO = parentGameService.getByPK(pgid);
					String parentGameName = "-";
					if (parentGameDO != null) {
						parentGameName = parentGameDO.getGname();
					}
					adRecoveryVo.setParentGameName(parentGameName);
				} catch (Exception e) {
					log.error("数据处理异常", e);
				}
			}
		}
	}

}
